﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Collections.Specialized;

namespace application.Tools
{
    public partial class updateItemImage : application.baseForm
    {
        public updateItemImage()
        {
            InitializeComponent();
            this.fromDirectoryEd.Text = CommonTypes.Settings.sysImagePathServer;
        }

        private bool DoValid()
        {
            bool retVal = true;
            ClearNotifyError();

            fromDirectoryEd.Text = fromDirectoryEd.Text.Trim();
            if (common.fileFuncs.PathExist(fromDirectoryEd.Text) == false)
            {
                NotifyError(fromDirectoryLbl);
                retVal = false;
            }
            if (common.StringLibs.IsNullOrEmpty(itemCodeSeparatorEd.Text))
            {
                NotifyError(itemCodeSeparatorLbl);
                retVal = false;
            }
            return retVal;
        }

        private DateTime myUpdateFilebeforeDate  = commonV2.Consts.constNullDate;
        private SortedList<string, List<string>> myImageList = new SortedList<string, List<string>>();

        private bool ProcessFileSearch (string fileName,bool isFolder)
        {
            if (isFolder) return true;

            if (this.myUpdateFilebeforeDate != commonV2.Consts.constNullDate &&
                File.GetCreationTime(fileName) <= this.myUpdateFilebeforeDate)
            {
                listBox1.Items.Add("Bỏ qua tệp cũ : " + fileName);
                return true;
            }

            //Get itemcode from file name
            string[] parts = commonV2.fileFuncs.FileNameOnly(fileName).Split(new string[] { itemCodeSeparatorEd.Text }, StringSplitOptions.RemoveEmptyEntries);
            if (parts.Length == 0) return false;

            //Check in database
            data.masterDS.ItemRow itemRow = DataAccess.DataCache.FindITEM(parts[0]);
            if (itemRow == null)
            {
                listBox1.Items.Add("Không có mã hàng : " + parts[0]);
                return true;
            }

            //Add to result list
            string relativeFileName = commonV2.fileFuncs.MakeRelativePath(this.fromDirectoryEd.Text, fileName);
            if (this.myImageList.Keys.Contains(itemRow.itemCode) == false)
            {
                this.myImageList.Add(itemRow.itemCode, new List<string>());
            }
            this.myImageList[itemRow.itemCode].Add(relativeFileName);
            return true;
        }

        private void DoUpdateImage()
        {
            this.ShowMessage("");
            listBox1.Items.Clear();
            this.myUpdateFilebeforeDate = newerThanDateEd.myDateTime; 
            this.myImageList.Clear();
            StringCollection searchPattern = common.StringLibs.Str2Collection(filePatternEd.Text);
            common.fileFuncs.SearchDirectory(fromDirectoryEd.Text, searchPattern, recursiveChk.Checked, ProcessFileSearch);

            if (newerThanDateChk.Checked == false) DataAccess.DataLibs.ResetItem_ImageList();
            SaveToDb();
        }

        private void SaveToDb()
        {
            foreach(string key in this.myImageList.Keys)
            {
                data.masterDS.ItemRow itemRow = DataAccess.DataCache.FindITEM(key);
                if (itemRow == null) continue;
                this.myImageList[key].Sort();

                string str = "";
                foreach (string fileName in this.myImageList[key])
                {
                    if (String.IsNullOrEmpty(str) == false) str += commonV2.Settings.sysSeparatorList[0].ToString();
                    str += fileName;
                }
                itemRow.imageList = str;
                DataAccess.DataLibs.UpdateData(itemRow);
                
                listBox1.Items.Add(itemRow.itemCode + "  -> " + itemRow.imageList);
            }
            listBox1.Items.Add(String.Format("Đã cập nhật hình cho {0} mã số.", this.myImageList.Count));
        }

        private void closeBtn_Click(object sender, EventArgs e)
        {
            this.Close();
        }
        private void okBtn_Click(object sender, EventArgs e)
        {
            try
            {
                okBtn.Enabled = false;
                if (DoValid() == false) return;
                DoUpdateImage();
            }
            catch (Exception er)
            {
                this.ShowError(er);
            }
            finally
            {
                okBtn.Enabled = true;
            }
        }
        private void newerThanDateChk_CheckedChanged(object sender, EventArgs e)
        {
            newerThanDateEd.Enabled = newerThanDateChk.Checked;
        }

        private void openBtn_Click(object sender, EventArgs e)
        {
            if (folderBrowserDialog.ShowDialog() != DialogResult.OK) return;
            this.fromDirectoryEd.Text = folderBrowserDialog.SelectedPath;
        }
    }
}
